package Impl

import (
	"encoding/json"
	"fmt"
	"go_code/map-collection-standalone/model/Entity"
	"io/ioutil"
	"os"
)

type MapEntityMapperImplByFileSystem struct {
	FilePrefix string
	FileSuffix string
}

func (this *MapEntityMapperImplByFileSystem) SelectById(id int64) (result Entity.MapEntity, err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(id) + this.FileSuffix
	_, err = os.Stat(filename)
	if os.IsNotExist(err) {
		return
	}
	jsonBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	err = json.Unmarshal(jsonBytes, &result)
	return
}

func (this *MapEntityMapperImplByFileSystem) Insert(mapEntity *Entity.MapEntity) (err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(mapEntity.Id) + this.FileSuffix
	file, err := os.Create(filename)
	defer file.Close()
	if err != nil {
		return err
	}
	jsonBytes, err := json.Marshal(mapEntity)
	if err != nil {
		return err
	}
	if _, err = file.Write(jsonBytes); err != nil {
		return err
	}
	return nil
}
func (this *MapEntityMapperImplByFileSystem) DeleteById(id int64) (err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(id) + this.FileSuffix
	return os.Remove(filename)
}
func (this *MapEntityMapperImplByFileSystem) Update(mapEntity *Entity.MapEntity) (err error) {
	object, err := this.SelectById(mapEntity.Id)
	if err != nil {
		return
	}
	object.Update(mapEntity)
	filename := this.FilePrefix + `\` + fmt.Sprint(mapEntity.Id) + this.FileSuffix
	file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return fmt.Errorf("打开文件时出错: %v", err)
	}
	defer file.Close()

	jsonBytes, err := json.Marshal(object)
	if err != nil {
		return fmt.Errorf("序列化对象时出错: %v", err)
	}
	// 将数据写入文件
	_, err = file.Write(jsonBytes)
	if err != nil {
		return fmt.Errorf("写入文件时出错: %v", err)
	}

	return nil
}
